package com.xuebusi.xpress.admin.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/redis")
public class RedisController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping(value = "/set", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject set(@RequestParam("key") String key, @RequestParam("value") String value) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", "success");
        jsonObject.put("time", System.currentTimeMillis());
        try {
            stringRedisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            jsonObject.put("message", e.toString());
        }
        return jsonObject;
    }

    @RequestMapping(value = "/get", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject get(@RequestParam("key") String key) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", "success");
        jsonObject.put("time", System.currentTimeMillis());
        String value;
        try {
            value = stringRedisTemplate.opsForValue().get(key);
            jsonObject.put("data", value);
        } catch (Exception e) {
            jsonObject.put("message", e.toString());
        }
        return jsonObject;
    }

}
